package com.tb.foryou;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ToxicBakery.viewpager.transforms.DepthPageTransformer;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class MainView extends ViewPager implements Runnable{

    private Context context;
    //mainView的集合
    private List<View> viewList;
    //存储每日语句
    private String[] books;
    //线程处理器
    private Handler handler = new Handler();

    /**
     * 初始化viewList
     * @param dayToStart
     *
     * viewList.get(0)  <====>  起始页
     * viewList.get(i)  <====>  第i天
     * viewList.get(books.length)  <====>  结尾页
     */
    public void init(int dayToStart){
        //获取每日语句
        books = getResources().getStringArray(R.array.books);
        //未加载完成的默认图片
        Bitmap bitmap = getBitmapByName(context,"icon");
        //起始页
        viewList.add(LayoutInflater.from(context).inflate(R.layout.main_view_head,null));
        //正常页
        for (int i = 0 ; i < dayToStart + 1; i++){
            //添加结尾页
            if(i == books.length){
                viewList.add(LayoutInflater.from(context).inflate(R.layout.main_view_last,null));
                break;
            }
            //一个mainView
            View view = LayoutInflater.from(context).inflate(R.layout.main_view,null);
            //文字
            ((TextView)view.findViewById(R.id.main_book)).setText(books[i]);
            //加载图片
            ImageView imgV = (ImageView) view.findViewById(R.id.imageView);
            imgV.setImageBitmap(bitmap);
            //缩放图片的宽度为手机宽度
            ViewGroup.LayoutParams para;
            para = imgV.getLayoutParams();
            para.width = getResources().getDisplayMetrics().widthPixels;
            para.height = (int) (para.width * 1.5);
            imgV.setLayoutParams(para);
            //将mainView加载到viewList中
            viewList.add(view);
        }

        //异步加载图片
        new Thread(this).start();
        //设置滑动方式
        this.setPageTransformer(true, new DepthPageTransformer());
        //设置适配器
        this.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return viewList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewList.get(position));

            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewList.get(position));
                return viewList.get(position);

            }
        });
        //添加页面改变监听器
        addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float onPageScrolled, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //设置当前页
        Log.d("当前页",viewList.size()-1 +"");
        this.setCurrentItem(viewList.size()-1);
    }
    //跳转页面
    public void goHeadPage(){
        this.setCurrentItem(0);
    }
    public void goNowPage(){
        this.setCurrentItem(viewList.size() - 1);
    }

    //构造函数
    public MainView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.viewList = new ArrayList<>();
        this.context = context;
    }

    //通过文件名加载drawable中的图片
    public Bitmap getBitmapByName(Context context, String name) {
        Class drawable  =  R.drawable.class;
        Field field;
        int resId = 0;
        try {
            field = drawable.getField(name);
            resId = field.getInt(field.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    //异步加载图片
    @Override
    public void run() {
        int viewListSize = viewList.size();
        //i记录了天数，减一是为了去掉起始页不算，0即为起始页
        for (int i = viewListSize - 1; i > 0; i--) {
            //结尾也已经加载过了,跳出继续
            if(i == books.length + 1){
                continue;
            }
            Log.d("打开页面:",i+"");
            //加载图片
            String name = "img_"+((i<10)?"0"+i:i);
            final Bitmap bitmap = getBitmapByName(context, name);
            final int finalI = i;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("加载图片:",finalI+"");
                    ImageView imgV = (ImageView) viewList.get(finalI).findViewById(R.id.imageView);
                    imgV.setImageBitmap(bitmap);
                }
            });
        }
    }
}
